#include <stdio.h>
///使用cmsis头文件
#include "ohos_init.h"
#include "cmsis_os2.h"

/* 互斥锁句柄id */
osMutexId_t g_testMux;
/* 任务ID */
osThreadId_t g_testTaskId01;
osThreadId_t g_testTaskId02;

void Example_MutexTask1(void *argument)
{
    osStatus_t ret;

    printf("task1 try to get  mutex, wait 10 ticks.\n");
    /* 申请互斥锁 */
    ret = osMutexAcquire(g_testMux, 10);

    if (ret == osOK) {
        printf("task1 get mutex g_testMux.\n");
        /* 释放互斥锁 */
        osMutexRelease(g_testMux);
        return;
    } else if (ret == osErrorTimeout) {
            printf("task1 timeout and try to get mutex, wait forever.\n");
            /* 申请互斥锁 */
            ret = osMutexAcquire(g_testMux, osWaitForever);
            if (ret == osOK) {
                printf("task1 wait forever, get mutex g_testMux.\n");
                /* 释放互斥锁 */
                osMutexRelease(g_testMux);
                return;
            }
    }
    return;
}

void Example_MutexTask2(void *argument)
{
    printf("task2 try to get  mutex, wait forever.\n");
    /* 申请互斥锁 */
    osMutexAcquire(g_testMux, osWaitForever);

    printf("task2 get mutex g_testMux and suspend 100 ticks.\n");

    /* 任务休眠100Ticks */
    osDelay(100);

    printf("task2 resumed and post the g_testMux\n");
    /* 释放互斥锁 */
    osMutexRelease(g_testMux);
    return;
}

uint32_t Example_TaskEntry(void)
{
    osStatus_t ret;
    osThreadAttr_t task1Attr;
    osThreadAttr_t task2Attr;
    osMutexAttr_t mutexAttr = {
        .name = "TestMutex",
        .attr_bits = 0U,
        .cb_mem = NULL,
        .cb_size = 0U
    };

    /* 创建互斥锁 */
    g_testMux = osMutexNew(&mutexAttr);

    /* 设置任务1属性 */
    task1Attr.name = "MutexTsk1";
    task1Attr.attr_bits = 0U;
    task1Attr.cb_mem = NULL;
    task1Attr.cb_size = 0U;
    task1Attr.stack_mem = NULL;
    task1Attr.stack_size = 4096; // 相当于LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE
    task1Attr.priority = osPriorityNormal;
    task1Attr.tz_module = 0;
    task1Attr.reserved = 0;

    /* 创建任务1 */
    g_testTaskId01 = osThreadNew(Example_MutexTask1, NULL, &task1Attr);
    if (g_testTaskId01 == NULL) {
        printf("task1 create failed.\n");
        return 1;
    }

    /* 设置任务2属性 */
    task2Attr.name = "MutexTsk2";
    task2Attr.attr_bits = 0U;
    task2Attr.cb_mem = NULL;
    task2Attr.cb_size = 0U;
    task2Attr.stack_mem = NULL;
    task2Attr.stack_size = 4096; // 相当于LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE
    task2Attr.priority = osPriorityAboveNormal; // 优先级高于任务1
    task2Attr.tz_module = 0;
    task2Attr.reserved = 0;

    /* 创建任务2 */
    g_testTaskId02 = osThreadNew(Example_MutexTask2, NULL, &task2Attr);
    if (g_testTaskId02 == NULL) {
        printf("task2 create failed.\n");
        return 1;
    }

    /* 延时300Ticks */
    osDelay(300);

    /* 删除互斥锁 */
    osMutexDelete(g_testMux);

    /* 删除任务1 */
    osThreadTerminate(g_testTaskId01);
    
    /* 删除任务2 */
    osThreadTerminate(g_testTaskId02);

    return 0;
}

APP_FEATURE_INIT(Example_TaskEntry);
